import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { User } from '../entity/User';

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class AuthDao {
    // 注入User实体的Repository
    @InjectEntityModel(User)
    userModel: Repository<User>;

    // 根据账号查找用户
    async findUserByAccount(account: string): Promise<User | null> {
        return await this.userModel.findOne({ 
            where: { account } 
        });
    }

    // 根据账号和密码验证用户
    async validateUser(account: string, password: string): Promise<User | null> {
        return await this.userModel.findOne({ 
            where: { 
                account, 
                password,
            } 
        });
    }

    // 创建新用户
    async createUser(userData: Partial<User>): Promise<User> {
        const user = this.userModel.create(userData);
        return await this.userModel.save(user);
    }

    // 根据ID查找用户
    async findUserById(id: string): Promise<User | null> {
        return await this.userModel.findOne({ 
            where: { id } 
        });
    }

    // 检查账号是否已存在
    async checkAccountExists(account: string): Promise<boolean> {
        const user = await this.userModel.findOne({ 
            where: { account } 
        });
        return !!user;
    }

    // 检查邮箱是否已存在
    async checkEmailExists(email: string): Promise<boolean> {
        const user = await this.userModel.findOne({ 
            where: { email } 
        });
        return !!user;
    }

    // 检查手机号是否已存在
    async checkPhoneExists(phone: string): Promise<boolean> {
        const user = await this.userModel.findOne({ 
            where: { phone } 
        });
        return !!user;
    }
}